package com.ios.service.impl;

import com.ios.mapper.SeatMapper;
import com.ios.model.entity.Seat;
import com.ios.service.SeatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class SeatServiceImpl implements SeatService {
    @Autowired
    private SeatMapper seatMapper;

    @Override
    public List<Seat> selectSeatList(Seat seat) {
        return seatMapper.selectSeatList(seat);
    }

    @Override
    public int insertSeat(Seat seat) {
        // 校验同一房间下行列是否已存在
        validateSeatUnique(seat);
        return seatMapper.insertSeat(seat);
    }

    @Override
    public int updateSeat(Seat seat) {
        // 校验同一房间下行列是否已存在（排除自己）
        validateSeatUnique(seat);
        return seatMapper.updateSeat(seat);
    }
    private void validateSeatUnique(Seat seat) {
        // 查询同一房间下相同行列的座位
        Seat query = new Seat();
        query.setRoomId(seat.getRoomId());
        query.setSRow(seat.getSRow());
        query.setSCol(seat.getSCol());

        List<Seat> existingSeats = seatMapper.selectSeatList(query);

        // 新增时直接校验
        if (seat.getId() == null && !existingSeats.isEmpty()) {
            throw new RuntimeException("该位置已存在座位");
        }

        // 修改时排除自身校验
        if (seat.getId() != null &&
                existingSeats.stream().anyMatch(s -> !s.getId().equals(seat.getId()))) {
            throw new RuntimeException("该位置已被其他座位占用");
        }
    }

    @Override
    public int deleteSeatByIds(Long[] ids) {
        return seatMapper.deleteSeatByIds(ids);
    }

    @Override
    public Seat selectSeatById(Long id) {
        return seatMapper.selectSeatById(id);
    }
}